package com.wonder.app.stock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wonder.common.constants.Constants;
import com.wonder.common.utils.CharsetKit;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.http.HttpUtils;



/**
 * Get the stock realtime data from the Datasource Privide
 * @author luzhongren
 *
 */
@Component
public class StockUtils {
	
	
	private static String sinaUrl="http://hq.sinajs.cn/list=";
	private static String imgUrl="http://sqt.gtimg.cn/utf8/q=r_";
	
	//For Shuhai data
	private static String shuhaiUrl="http://shapi.market.alicloudapi.com/stock?u=daniu&";
	private static String authorization = "APPCODE 6a8f13cf5c71423996264ec52cd72a7c"; 
	

	
	/**
	 * 依据股票代码取得股票价格
	 * @param code
	 * @return 实时股票价格
	 */
	public static StockPrice getPrice(String code)
	{
		return getImgPrice(code);
	}
	
	
	private static StockPrice getSinaPrice(String code)
	{
		String sendGet = HttpUtils.sendGet(sinaUrl+code, "",CharsetKit.GBK);
		String[] fcs = sendGet.split("\"");          //按"号分割字符
        String scs = fcs[1];       
        String[] v = scs.split(",");          //按,号分割字符
        
        String s1 = fcs[0];
	    int j = s1.indexOf("=");  
	    String shortCode = s1.substring(11, j);//获取CODE
	      
		StockPrice price=new StockPrice();
		price.setName(v[0]);
		price.setLow(Double.parseDouble(v[5]));
		price.setHigh(Double.parseDouble(v[4]));
		
		price.setBP1(Double.parseDouble(v[11]));
		price.setBP2(Double.parseDouble(v[13]));
		price.setBP3(Double.parseDouble(v[15]));
		price.setBP4(Double.parseDouble(v[17]));
		price.setBP5(Double.parseDouble(v[19]));
		price.setBV1(Integer.parseInt(v[10]));
		price.setBV2(Integer.parseInt(v[12]));
		price.setBV3(Integer.parseInt(v[14]));
		price.setBV4(Integer.parseInt(v[16]));
		price.setBV5(Integer.parseInt(v[18]));
	
		price.setSP2(Double.parseDouble(v[21]));
		price.setSP3(Double.parseDouble(v[23]));
		price.setSP4(Double.parseDouble(v[25]));
		price.setSP5(Double.parseDouble(v[27]));
		price.setSP1(Double.parseDouble(v[29]));
		
		price.setSV1(Integer.parseInt(v[20]));
		price.setSV2(Integer.parseInt(v[22]));
		price.setSV3(Integer.parseInt(v[24]));
		price.setSV4(Integer.parseInt(v[26]));
		price.setSV5(Integer.parseInt(v[28]));
		
		price.setNewPrice(Double.parseDouble(v[3]));
		price.setLastClose(Double.parseDouble(v[2]));
		price.setOpen(Double.parseDouble(v[1]));
		price.setSymbol(shortCode);
		
		price.setAmount(Double.parseDouble(v[9]));
		price.setVolume(Double.parseDouble(v[8]));
		price.setTime(DateUtils.strToDate(v[30]+v[31], "yyyy-MM-ddHH:mm:ss"));
		
		return price;		
	}
	
	public static HashMap<String,StockPrice> getSinaPrices(String codes){
		String sendGet = HttpUtils.sendGet(sinaUrl+codes, "",CharsetKit.GBK);
		HashMap<String,StockPrice> prices=new HashMap<>();
		String[] vs=sendGet.split(";");
		for(int i=0;i<vs.length;i++)
		{
			String[] fcs = sendGet.split("\"");          //按"号分割字符
			StockPrice price=new StockPrice();
			
			String scs = fcs[1];       
		    String[] v = scs.split(",");          //按,号分割字符
			
			String s1 = fcs[0];
		    int j = s1.indexOf("=");  
		    String shortCode = s1.substring(11, j);//获取CODE
		    price.setName(v[0]);
			price.setLow(Double.parseDouble(v[5]));
			price.setHigh(Double.parseDouble(v[4]));
			
			price.setBP1(Double.parseDouble(v[11]));
			price.setBP2(Double.parseDouble(v[13]));
			price.setBP3(Double.parseDouble(v[15]));
			price.setBP4(Double.parseDouble(v[17]));
			price.setBP5(Double.parseDouble(v[19]));
			price.setBV1(Integer.parseInt(v[10]));
			price.setBV2(Integer.parseInt(v[12]));
			price.setBV3(Integer.parseInt(v[14]));
			price.setBV4(Integer.parseInt(v[16]));
			price.setBV5(Integer.parseInt(v[18]));
		
			price.setSP2(Double.parseDouble(v[21]));
			price.setSP3(Double.parseDouble(v[23]));
			price.setSP4(Double.parseDouble(v[25]));
			price.setSP5(Double.parseDouble(v[27]));
			price.setSP1(Double.parseDouble(v[29]));
			
			price.setSV1(Integer.parseInt(v[20]));
			price.setSV2(Integer.parseInt(v[22]));
			price.setSV3(Integer.parseInt(v[24]));
			price.setSV4(Integer.parseInt(v[26]));
			price.setSV5(Integer.parseInt(v[28]));
			
			price.setNewPrice(Double.parseDouble(v[3]));
			price.setLastClose(Double.parseDouble(v[2]));
			price.setOpen(Double.parseDouble(v[1]));
			price.setSymbol(shortCode);
			
			price.setAmount(Double.parseDouble(v[9]));
			price.setVolume(Double.parseDouble(v[8]));
			price.setTime(DateUtils.strToDate(v[30]+v[31], "yyyy-MM-ddHH:mm:ss"));
			
			prices.put(shortCode, price);
		    
			
		}
		
		
		
		return prices;
		
		
	}
	
	public static void getShuhaiFinance(String code) {
		 String url = shuhaiUrl +"type=finance&symbol=" + code.toUpperCase() ;
		    
		
		    
		    String httpGet=HttpUtils.httpGet(url, "", authorization);
		    System.out.println(httpGet);

		  	
	}
	
	/**
	 * Get the real time trend line
	 * @param code
	 * @param date
	 * @return
	 */
	public static List<Trend>getShuhaiTrend(String code,Integer date)
	{	
	    String url = shuhaiUrl +"type=trend&symbol=" + code.toUpperCase() ;
	    
	    if(date !=null) url=url + "&date=" +date.toString();//For the fix date
	
	    
	    String httpGet=HttpUtils.httpGet(url, "", authorization);
	    System.out.println(httpGet);
	    if(StringUtils.isBlank(httpGet)) return null;
	    if(httpGet.indexOf("[{") <0)return null;
	    httpGet=httpGet.substring(httpGet.indexOf("[{"),httpGet.length()-1);

	    List<Trend> trends= JSON.parseObject(httpGet, new TypeReference<List<Trend>>() {});
		
		return trends;		
	}
	
	
	/**
	 * Get the Split data for the stock code
	 * @return
	 */
	public static List<Split>getShuhaiSplit(String code,Integer fromDate,Integer toDate)
	{

	    String url = shuhaiUrl +"type=split&symbol=" + code.toUpperCase() ;
	    
	    if(fromDate !=null) url=url + "&st=" +fromDate.toString();
	    if(toDate !=null) url=url + "&et=" +toDate.toString();
	    
	    String httpGet=HttpUtils.httpGet(url, "", authorization);
	    
	    System.out.println(httpGet);
	    
	    List<Split> splits= JSON.parseObject(httpGet, new TypeReference<List<Split>>() {});
		
		return splits;		
	}
	
	
	/**
	 * Get the kline data for the stock code
	 * @return
	 */
	public static List<Kline>getShuhaiKline(String code,String lineType,Integer num,Integer fromDate,Integer toDate)
	{
		String kValString = getKValueByString(lineType);
	    String url = shuhaiUrl +"type=kline&symbol=" + code.toUpperCase() + "&num="+num+"&line="+kValString;
	    
	    if(fromDate !=null) url=url + "&st=" +fromDate.toString();
	    if(toDate !=null) url=url + "&et=" +toDate.toString();
	    
	    String httpGet=HttpUtils.httpGet(url, "", authorization);
	    
	    List<Kline> klines= JSON.parseObject(httpGet, new TypeReference<List<Kline>>() {});
		
		return klines;		
	}
	
	private static String getKValueByString(String kValue) {
		String returnVal = "";

		switch (kValue) {
		case "M1":
			returnVal = "min,1";
			break;
		case "M5":
			returnVal = "min,5";
			break;
		case "M15":
			returnVal = "min,15";
			break;
		case "M30":
			returnVal = "min,30";
			break;
		case "H1":
			returnVal = "min,60";
			break;
		case "D1":
			returnVal = "day,1";
			break;
		case "R1":
			returnVal = "trend";
			break;
		default:
			returnVal = "trend";
			break;
		}

		return returnVal;
	}
	
	/**
	 * Get the detail data of the stock. 
	 * @param code
	 * @return
	 */
	public static List<StockPrice> getShuhaiPrice(String code)
	{
		List<StockPrice> prices=new ArrayList<StockPrice>();
		
		String url = shuhaiUrl + "type=stock&symbol=" + code.toUpperCase(); // URL with parameters comma separated also

		String httpGet=HttpUtils.httpGet(url, "", authorization);
		
		//System.out.println(httpGet);
		JSONArray jsonArray=JSONArray.parseArray(httpGet);
		for(int i=0;i<jsonArray.size();i++)
		{
			StockPrice price=new StockPrice();	
			JSONObject jo = jsonArray.getJSONObject(i);
			
			price.setName(jo.getString("Name"));
			price.setLow(jo.getDouble("Low"));
			price.setHigh(jo.getDouble("High"));
			
			price.setBP1(jo.getDouble("BP1"));
			price.setBP2(jo.getDouble("BP2"));
			price.setBP3(jo.getDouble("BP3"));
			price.setBP4(jo.getDouble("BP4"));
			price.setBP5(jo.getDouble("BP5"));
			price.setBV1(jo.getInteger("BV1"));
			price.setBV2(jo.getInteger("BV2"));
			price.setBV3(jo.getInteger("BV3"));
			price.setBV4(jo.getInteger("BV4"));
			price.setBV5(jo.getInteger("BV5"));
			
			price.setSP1(jo.getDouble("SP1"));
			price.setSP2(jo.getDouble("SP2"));
			price.setSP3(jo.getDouble("SP3"));
			price.setSP4(jo.getDouble("SP4"));
			price.setSP5(jo.getDouble("SP5"));
			
			price.setSV1(jo.getInteger("SV1"));
			price.setSV2(jo.getInteger("SV2"));
			price.setSV3(jo.getInteger("SV3"));
			price.setSV4(jo.getInteger("SV4"));
			price.setSV5(jo.getInteger("SV5"));
			
			price.setNewPrice(jo.getDouble("NewPrice"));
			price.setLastClose(jo.getDouble("LastClose"));
			price.setOpen(jo.getDouble("Open"));
			price.setSymbol(jo.getString("Symbol").toLowerCase());
			
			price.setAmount(jo.getDouble("Amount"));
			price.setVolume(jo.getDouble("Volume"));
			price.setTime(DateUtils.longToDate(Long.parseLong(jo.getString("Date"))*1000));
			
			price.setPriceChangeRatio(jo.getDouble("PriceChangeRatio"));
			
			prices.add(price);
			
		}
		
		return prices;		
	}
	
	
	
	private static StockPrice getImgPrice(String code)
	{
		String sendGet = HttpUtils.sendGet(imgUrl+code, "",CharsetKit.UTF_8);
		String[] v = sendGet.split("~");
		StockPrice price=new StockPrice();
		
		String s1 = v[0];
	    int i = s1.indexOf("=");
	    String shortCode = s1.substring(2, i);
	        
		price.setName(v[1]);
		price.setLow(Double.parseDouble(v[42]));
		price.setHigh(Double.parseDouble(v[41]));
		
		price.setBP1(Double.parseDouble(v[9]));
		price.setBP2(Double.parseDouble(v[11]));
		price.setBP3(Double.parseDouble(v[13]));
		price.setBP4(Double.parseDouble(v[15]));
		price.setBP5(Double.parseDouble(v[17]));
		price.setBV1(Integer.parseInt(v[10]));
		price.setBV2(Integer.parseInt(v[12]));
		price.setBV3(Integer.parseInt(v[14]));
		price.setBV4(Integer.parseInt(v[16]));
		price.setBV5(Integer.parseInt(v[18]));
		
		price.setSP1(Double.parseDouble(v[19]));
		price.setSP2(Double.parseDouble(v[21]));
		price.setSP3(Double.parseDouble(v[23]));
		price.setSP4(Double.parseDouble(v[25]));
		price.setSP5(Double.parseDouble(v[27]));
		
		price.setSV1(Integer.parseInt(v[20]));
		price.setSV2(Integer.parseInt(v[22]));
		price.setSV3(Integer.parseInt(v[24]));
		price.setSV4(Integer.parseInt(v[26]));
		price.setSV5(Integer.parseInt(v[28]));
		
		price.setNewPrice(Double.parseDouble(v[3]));
		price.setLastClose(Double.parseDouble(v[4]));
		price.setOpen(Double.parseDouble(v[5]));
		price.setSymbol(shortCode);
		
		price.setAmount(Double.parseDouble(v[37]));
		price.setVolume(Double.parseDouble(v[36]));
		price.setTime(DateUtils.strToDate(v[30], "yyyyMMddHHmmss"));
		
		price.setPriceChangeRatio(Double.parseDouble(v[31]));
		
		return price;
	}
	
	public static HashMap<String,StockPrice> getImgPrices(String codes)
	{
		HashMap<String,StockPrice> prices=new HashMap<>();
		String sendGet = HttpUtils.sendGet(imgUrl+codes, "",CharsetKit.UTF_8);
		String[] vs=sendGet.split(";");
		for(int i=0;i<vs.length;i++)
		{
			String[] v=vs[i].split("~");
			StockPrice price=new StockPrice();
			
			String s1 = v[0];
		    int j = s1.indexOf("=");
		    String shortCode = s1.substring(2, j);
		    
			price.setName(v[1]);
			price.setLow(Double.parseDouble(v[42]));
			price.setHigh(Double.parseDouble(v[41]));
			
			price.setBP1(Double.parseDouble(v[9]));
			price.setBP2(Double.parseDouble(v[11]));
			price.setBP3(Double.parseDouble(v[13]));
			price.setBP4(Double.parseDouble(v[15]));
			price.setBP5(Double.parseDouble(v[17]));
			price.setBV1(Integer.parseInt(v[10]));
			price.setBV2(Integer.parseInt(v[12]));
			price.setBV3(Integer.parseInt(v[14]));
			price.setBV4(Integer.parseInt(v[16]));
			price.setBV5(Integer.parseInt(v[18]));
			
			price.setSP1(Double.parseDouble(v[19]));
			price.setSP2(Double.parseDouble(v[21]));
			price.setSP3(Double.parseDouble(v[23]));
			price.setSP4(Double.parseDouble(v[25]));
			price.setSP5(Double.parseDouble(v[27]));
			
			price.setSV1(Integer.parseInt(v[20]));
			price.setSV2(Integer.parseInt(v[22]));
			price.setSV3(Integer.parseInt(v[24]));
			price.setSV4(Integer.parseInt(v[26]));
			price.setSV5(Integer.parseInt(v[28]));
			
			price.setNewPrice(Double.parseDouble(v[3]));
			price.setLastClose(Double.parseDouble(v[4]));
			price.setOpen(Double.parseDouble(v[5]));
			price.setSymbol(shortCode);
			
			price.setAmount(Double.parseDouble(v[37]));
			price.setVolume(Double.parseDouble(v[36]));
			price.setTime(DateUtils.strToDate(v[30], "yyyyMMddHHmmss"));
			
			price.setPriceChangeRatio(Double.parseDouble(v[31]));
			prices.put(shortCode, price);
			
		}
		
		
		return prices;
	}
	
	/**
	 * 用多个股票代码取得多个实时股票价格数据
	 * @param codes 股票代码字符串，用逗号分割
	 * @return 股票代码/股票数据哈希列表
	 */
	
	public static HashMap<String,StockPrice> getPrices(String codes)
	{
	   return getImgPrices(codes);
	}
//	/**
//	 * 获取持仓市值
//	 * @param prices：实时价格
//	 * @param list：持仓列表
//	 * @return
//	 */
//
//	public static HashMap<String,Object> marketProfit(HashMap<String,StockPrice> prices,List<Depot> list){
//		HashMap<String,Object> markets=new HashMap<>();
//		
//		Double market=0.;
//		Double profitLoss=0.;
//		Integer stopped=0;
//		
//		for(Depot vo:list)
//		{
//			String code=vo.getCode();
//			Double price=prices.get(code).getNewPrice();
//			if(price<=0)
//			{
//				stopped++;
//			}else
//			{
//				market +=(vo.getSurplus() +vo.getFrozen()) * price;
//				profitLoss +=(vo.getSurplus() +vo.getFrozen()) * (price-vo.getPrice());
//			}
//			
//
//		}
//		markets.put("market", market);
//		markets.put("profit", profitLoss);
//		markets.put("stopped", stopped);
//		
//		return markets;
//	}
//	
//	/**
//	 * 获取持仓市值
//	 * @param list：持仓列表
//	 * @return
//	 */
//	public static HashMap<String,Object> marketProfi(List<Depot> list)
//	{
//		HashMap<String,Object> markets=new HashMap<>();
//		List<String> codeList=new ArrayList<>();
//		for(Depot vo:list)
//		{
//			String code=vo.getCode();
//			if(codeList.contains(code)) continue;
//			codeList.add(code);
//
//		}
//		String codes=StringUtils.join(codeList.toArray(), ",");
//		
//		HashMap<String,StockPrice> prices=getPrices(codes);
//		Double market=0.;
//		Double profitLoss=0.;
//		Integer stopped=0;
//		
//		for(Depot vo:list)
//		{
//			String code=vo.getCode();
//			Double price=prices.get(code).getNewPrice();
//			if(price<=0)
//			{
//				stopped++;
//			}else
//			{
//				market +=(vo.getSurplus() +vo.getFrozen()) * price;
//				profitLoss +=(vo.getSurplus() +vo.getFrozen()) * (price-vo.getPrice());
//			}
//			
//
//		}
//		markets.put("market", market);
//		markets.put("profit", profitLoss);
//		markets.put("stopped", stopped);
//		
//		return markets;
//	}
	
   

}
